package com.zyd.netty;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Splitter;
import com.zyd.context.AppContext;
import com.zyd.dao.SocketNowBlackCarDao;
import com.zyd.io.model.*;
import com.zyd.mappers.*;
import com.zyd.service.blackcar.impl.BlackCarServiceImpl;
import com.zyd.service.enclosure.impl.EnclosureServiceImpl;
import com.zyd.util.SnowFlakeId;
import com.zyd.util.ToolUtils;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

@ChannelHandler.Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    private static final Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();

    private static final Splitter SAPCE_SPLITTER = Splitter.on(' ').trimResults().omitEmptyStrings();

    private static final Logger LOGGER = LoggerFactory.getLogger(DuplexNettyServer.class);

    /*
     * 收到消息时，返回信息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg)
            throws Exception {
        // 收到消息直接打印输出
        LOGGER.info("服务端接受的消息 : " + msg);
        if ("quit".equals(msg)) {//服务端断开的条件
            ctx.close();
        }

        ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[]{1}));
        //处理数据
        processData(msg);
    }

    /*
     * 建立连接时，返回消息
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("连接的客户端地址:" + ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }

    private void processData(String message) {
        try {
            doProcess(message);
        } catch (Exception e) {
            LOGGER.error("处理数据失败,message:" + message, e);
        }
    }

    private void doProcess(String message) {
        List<String> msg = SPLITTER.splitToList(message);
        String eventType = SAPCE_SPLITTER.splitToList(msg.get(0)).get(1).trim();
        String stationId = msg.get(1);


        SocketNowEntity entity = new SocketNowEntity();
        entity.setEvent_type(eventType);
        entity.setBase_id(stationId);

        if (eventType.equals("4000")||eventType.equals("4040")) {
            //如果事件类型是4000,心跳包
            proccessHeartData(entity);
        } else {
            String stationVersion = msg.get(2);
            String tagId = msg.get(3);
            String tagVersion = msg.get(4);
            String bak1 = msg.get(5);

            entity.setBase_version(stationVersion);
            entity.setTag_id(tagId);
            entity.setTag_version(tagVersion);
            entity.setBak_1(bak1);
            entity.setRec_time(new Date());
            /**
             * 采用分布式id生成器生成id
             */
            entity.setId(new SnowFlakeId().nextId());
            proccessRecordData(entity);
            proccessHeartData(entity);

        }

    }

    private void proccessHeartData(SocketNowEntity entity) {
        String stationcode = entity.getBase_id();
        StationEntityExample example = new StationEntityExample();
        example.or().andStationcodeEqualTo(stationcode).andDrEqualTo(0);
        StationEntityMapper stationEntityMapper = AppContext.getContext().getBean(StationEntityMapper.class);

        StationEntity en = new StationEntity();
        en.setStationstatus("正常");
        en.setRegtime(ToolUtils.getNowTime());

        stationEntityMapper.updateByExampleSelective(en, example);

    }

    private void proccessRecordData(SocketNowEntity entity) {
        LOGGER.info("开始插入数据库，socket_now数据:" + JSON.toJSONString(entity));
        SocketNowEntityMapper mapper = AppContext.getContext().getBean(SocketNowEntityMapper.class);
        entity.setEvent_type("1000");
        mapper.insertSelective(entity);
        boolean isBlackCar = false;


        VehicleRecordEntity recordEntity = new VehicleRecordEntity();
        recordEntity.setStationcode(entity.getBase_id());

        StationEntityMapper stationEntityMapper = AppContext.getContext().getBean(StationEntityMapper.class);
        StationEntityExample entityExample = new StationEntityExample();
        entityExample.or().andStationcodeEqualTo(entity.getBase_id()).andDrEqualTo(0);
//        LOGGER.info("基站baseid:" + entity.getBase_id());
        List<StationEntity> stationEntities = stationEntityMapper.selectByExample(entityExample);

        if (stationEntities.size() == 0) {
//            LOGGER.error("基站信息不存在,stationcode:" + entity.getBase_id());
            recordEntity.setStationcode(entity.getBase_id());
        } else {
            StationEntity stationEntity = stationEntities.get(0);
            recordEntity.setStationid(stationEntity.getStationid());
        }

        VehicleEntityMapper vehicleEntityMapper = AppContext.getContext().getBean(VehicleEntityMapper.class);
        VehicleEntityExample vehicleEntityExample = new VehicleEntityExample();
        vehicleEntityExample.or().andTagcodeEqualTo(entity.getTag_id()).andDrEqualTo(0);
        List<VehicleEntity> vehicleEntities = vehicleEntityMapper.selectByExample(vehicleEntityExample);
        if (vehicleEntities.size() == 0) {
//            LOGGER.error("车辆信息不存在,tagcode:" + entity.getTag_id());
        } else {
            recordEntity.setVehiclid(vehicleEntities.get(0).getId());
        }

        recordEntity.setTs(ToolUtils.getNowTime());
        recordEntity.setTagcode(entity.getTag_id());
        recordEntity.setDr(0);
        recordEntity.setCreatetime(ToolUtils.getNowTime());
        //2018-11-03 数据库字段为10，暂时不插入
//        recordEntity.setBilldate(ToolUtils.getNowTime());
        recordEntity.setRegtime(new Date());

        BlackCarEntityMapper blackCarEntityMapper = AppContext.getContext().getBean(BlackCarEntityMapper.class);
        BlackCarEntityExample example = new BlackCarEntityExample();
        example.or().andTagcodeEqualTo(entity.getTag_id()).andDrEqualTo(0).andStateEqualTo(0);
        List<BlackCarEntity> blackCarEntities = blackCarEntityMapper.selectByExample(example);
        if (blackCarEntities.size() > 0) {
            isBlackCar=true;
            recordEntity.setState(1);
            recordEntity.setIslock(1);
            recordEntity.setIswarn(0);
            //向黑车轨迹表插入数据
            SocketNowBlackCarDao socketNowBlackCarDao = AppContext.getContext().getBean(SocketNowBlackCarDao.class);
            socketNowBlackCarDao.save(entity);
            BlackCarServiceImpl blackCarService = AppContext.getContext().getBean(BlackCarServiceImpl.class);

            VehicleRecordEntityMapper vehicleRecordEntityMapper = AppContext.getContext().getBean(VehicleRecordEntityMapper.class);
//        LOGGER.info("开始插入数据库，vehicle_record数据:" + JSON.toJSONString(recordEntity));
            vehicleRecordEntityMapper.insertSelective(recordEntity);
            blackCarService.smsInfo(entity.getBase_id(),entity.getTag_id());
        }
        EnclosureServiceImpl enclosureService = AppContext.getContext().getBean(EnclosureServiceImpl.class);
        enclosureService.vehicleCounting(entity.getTag_id(),entity.getBase_id(),isBlackCar);


    }



}
